<?php
namespace app\dboard\controller;
use think\captcha;
use think\facade\Cookie;
use think\facade\Session;
use think\facade\Url;
use think\Db;
use services\ImmService;
class Acourseware extends Base
{
    public function initialize() {
        parent::initialize();
        $returnUrl=Url::build('dboard/alogin/sign');
        if(!isset($this->AdminAccount['AdminID']) || intval($this->AdminAccount['AdminID'])<=0 || !isset($this->AdminAccount['PAdminID'])){
            if($this->request->isAjax()){
                return $this->print_result(['Code'=>9999,'Msg'=>'请登录']);
            }
            return $this->redirect($returnUrl);
        }
    }
    public function add_courseware(){
        $courseware_type = Db::name('courseware_type')->where(['status'=>1])->select();
        $courseware_course = Db::name('courseware_course')->where(['status'=>1,'pid'=>0])->select();
        $this->assign('courseware_type',$courseware_type);
        $this->assign('courseware_course',$courseware_course);
        return view('acourseware/add_courseware');
    }
    public function edit_courseware(){
        $input = $this->request->param(false);
        $id = isset($input['id'])?$input['id']:0;
        $courseware = [];
        if (!$id) {
            return $this->print_result(['Code'=>1,'Msg'=>'缺少参数']);
        }
        $courseware = Db::name('courseware')->where(['id'=>$id])->find();
        if (isset($courseware['file']) && $courseware['file']) {
            $courseware['file'] = json_decode($courseware['file'],1);
            if (is_array($courseware['file']) && count($courseware['file'])) {
                foreach ($courseware['file'] as $key => &$value) {
                    $value[3] = config('upload_domain').$value[1];
                }
            }
        }
        $courseware_type = Db::name('courseware_type')->where(['status'=>1])->select();
        $courseware_course = Db::name('courseware_course')->where(['status'=>1,'pid'=>0])->select();
        $pid3 = $courseware['course_id'];
        $pid2 = Db::name('courseware_course')->where(['id'=>$pid3])->value('pid');
        $pid1 = Db::name('courseware_course')->where(['id'=>$pid2])->value('pid');
        $this->assign('courseware_type',$courseware_type);
        $this->assign('courseware_course',$courseware_course);
        $this->assign('courseware',$courseware);
        $this->assign('pid1',$pid1);
        $this->assign('pid2',$pid2);
        $this->assign('pid3',$pid3);
        return view('acourseware/edit_courseware');
    }
    public function courseware_info(){
        // $argv = [];
        // $res = (new ImmService())::main(array_slice($argv, 1));
        // $arr['previewURL'] = $res->body->previewURL;
        // $arr['refreshToken'] = $res->body->refreshToken;
        // $arr['requestId'] = $res->body->requestId;
        // $arr['accessToken'] = $res->body->accessToken;
        // $arr['refreshTokenExpiredTime'] = $res->body->refreshTokenExpiredTime;
        // $arr['accessTokenExpiredTime'] = $res->body->accessTokenExpiredTime;
        



        $input = $this->request->param(false);
        $id = isset($input['id'])?$input['id']:0;
        $courseware = [];
        if (!$id) {
            return $this->print_result(['Code'=>1,'Msg'=>'缺少参数']);
        }
        $courseware = Db::name('courseware')->where(['id'=>$id])->find();
        $courseware['has_video'] = 0;
        $courseware['has_pdf'] = 0;
        $courseware['video'] = [];
        $courseware['pdf'] = [];
        if (isset($courseware['file']) && $courseware['file']) {
            $courseware['file'] = json_decode($courseware['file'],1);
            if (is_array($courseware['file']) && count($courseware['file'])) {
                foreach ($courseware['file'] as $key => &$value) {
                    $multi_file = [];
                    $ex = explode(',', trim($value[1]));
                    if (count($ex)) {
                        foreach ($ex as $k => &$mf) {
                            // if (explode('.', $mf)[1]!='ppt' && explode('.', $mf)[1]!='pptx') continue;
                            $mf_name = Db::name('file')->where(['path'=>$mf])->value('name');
                            if (!$mf_name) {
                                if ($value[2]=='视频') {
                                    $mf_name = '视频';
                                } else {
                                    $mf_name = '文件';
                                }
                            }
                            $mf = config('upload_domain').$mf;
                            $multi_file[$k] = ['mf_name'=>$mf_name,'mf'=>$mf];
                        }
                    }
                    $value[3] = $multi_file;
                    if ($value[2]=='视频') {
                        $courseware['has_video'] = 1;
                        $courseware['video'] = array_merge($courseware['video'],$multi_file);
                    } else {
                        $courseware['has_pdf'] = 1;
                        $courseware['pdf'] = array_merge($courseware['pdf'],$multi_file);
                    }
                }
            }
        }
        $pid3 = $courseware['course_id'];
        $courseware_course_name3 = $courseware['course'];
        $courseware_course2 = Db::name('courseware_course')->where(['id'=>$pid3])->field('pid,name')->find();
        $pid2 = $courseware_course2['pid'];
        $courseware_course_name2 = $courseware_course2['name'];
        $courseware_course1 = Db::name('courseware_course')->where(['id'=>$pid2])->field('pid,name')->find();
        $pid1 = $courseware_course2['pid'];
        $courseware_course_name1 = $courseware_course1['name'];
        // $this->assign('arr',$arr);
        $this->assign('courseware',$courseware);
        $this->assign('pid1',$pid1);
        $this->assign('pid2',$pid2);
        $this->assign('pid3',$pid3);
        $this->assign('courseware_course_name1',$courseware_course_name1);
        $this->assign('courseware_course_name2',$courseware_course_name2);
        $this->assign('courseware_course_name3',$courseware_course_name3);
        return view('acourseware/courseware_info');
    }
    public function authorize_list(){
        return view('acourseware/authorize_list');
    }
    public function authorizelist()
    {
        $sid = $this->request->param('sid');
        $start_time = '';
        $end_time = '';
        $courseware_authorize = Db::name('courseware_authorize')->where(['sid'=>$sid,'type'=>1,'status'=>1])->find();
        if ($courseware_authorize) {
            $start_time = date('Y-m-d H:i',$courseware_authorize['start_time']);
            $end_time = date('Y-m-d H:i',$courseware_authorize['end_time']);
        }
        $this->assign('start_time',$start_time);
        $this->assign('end_time',$end_time);
        $this->assign('sid',$sid);
        return view('acourseware/authorizelist');
    }
    public function authorize(){
        if ($this->request->isPost()) {
            $courseware = Db::name('courseware')->where('id',$id)->find();
            $store = Db::name('store')->where(['status'=>1])->select();
            // 已授权的店
            $courseware_authorize = Db::name('courseware_authorize')->where(['courseware_id'=>$id,'status'=>1,'type'=>1])->select();
            return $this->print_result(['Code'=>0,'Msg'=>'成功','Data'=>['courseware'=>$courseware,'store'=>$store,'courseware_authorize'=>$courseware_authorize]]);
        }
        $input = $this->request->param(false);
        $id = isset($input['id'])?$input['id']:0;
        $courseware = [];
        if (!$id) {
            return $this->print_result(['Code'=>1,'Msg'=>'缺少参数']);
        }
        $courseware = Db::name('courseware')->where('id',$id)->find();
        $store = Db::name('store')->where(['status'=>1])->select();
        if ($store) {
            foreach ($store as $key => &$value) {
                $value['wxcode'] = config('http_domain').$value['wxcode'];
            }
        }
        // 已授权的店
        $courseware_authorize = Db::name('courseware_authorize')->where(['courseware_id'=>$id,'status'=>1,'type'=>1])->value('group_concat(sid) as sid');
        $this->assign('id',$id);
        $this->assign('courseware',$courseware);
        $this->assign('store',$store);
        $this->assign('courseware_authorize',$courseware_authorize);
        return view('acourseware/authorize');
    }
    public function coursewareLists(){
        return view('acourseware/lists');
    }
    public function doCreateCourseware(){
        if (!$this->request->isAjax()) {
            $this->res_data['Msg'] = '请求方式错误';
            return $this->print_result($this->res_data);
        }
        $param    = $this->request->param(false);
        $acourseware= Controller('Acourseware', 'logic');
        $result            = $acourseware->create($param);
        return $this->print_result($result);
    }
    public function ajaxList(){
        if (!$this->request->isAjax()) {
            $this->res_data['Msg'] = '请求方式错误';
            return $this->print_result($this->res_data);
        }
        $input = $this->request->param(false);
        $page_limit      = isset($input['length'])?$input['length']:10;
        $page_start      = isset($input['start'])?$input['start']:0;
        $p = 1;
        if ($page_start > 0) {
            $p = ceil($page_start / ($page_limit - 1));
        }
        $where[] = ['status','=',1];
        // $where[] = ['file','like','%ppt%'];
        $count=Db::name('courseware')->where($where)->count();
        $list  = Db::name('courseware')
              ->where($where)
              ->order('id ASC')
              ->limit($page_start, $page_limit)->select();
        foreach($list as &$v){
            $v['create_date'] = date('Y-m-d H:i',$v['create_time']);
            $v['authorize_store'] = Db::name('courseware_authorize')->alias('ca')->leftJoin('store s','s.id=ca.sid')->where(['ca.course_id'=>$v['course_id'],'ca.status'=>1,'ca.type'=>1])->value('group_concat(s.name)');
            if (!$v['authorize_store']) {
                $v['authorize_store'] = '';
            }
            $file = json_decode($v['file'],1);
            $v['content'] = '';
            if (count($file)) {
                foreach ($file as $key => $value) {
                    if (isset($value[2]))
                        $v['content'] .= $value[2].',';
                }
                $v['content'] = trim($v['content'],',');
            }
        }
        
        $this->res_data['Msg']='OK';
        $this->res_data['Code']=0;
        $this->res_data['Data']=['courseware'=>$list,'Data'=>$list,'recordsTotal'=>$count];
        $this->res_data['recordsTotal']=$count;
        return $this->print_result($this->res_data);
    }
    public function edit(){
        if (!$this->request->isAjax()) {
            $this->res_data['Msg'] = '请求方式错误';
            return $this->print_result($this->res_data);
        }
        $param    = $this->request->param(false);
        $acourseware= Controller('Acourseware', 'logic');
        $result            = $acourseware->edit($param);
        return $this->print_result($result);
    }
    public function info(){
        if (!$this->request->isAjax()) {
            $this->res_data['Msg'] = '请求方式错误';
            return $this->print_result($this->res_data);
        }
        $param    = $this->request->param(false);
        $acourseware= Controller('Acourseware', 'logic');
        $result            = $acourseware->coursewareInfo($param);
        return $this->print_result($result);
    }
    public function updateCourseware(){
        if (!$this->request->isAjax()) {
            $this->res_data['Msg'] = '请求方式错误';
            return $this->print_result($this->res_data);
        }
        $param    = $this->request->param(false);
        $acourseware= Controller('Acourseware', 'logic');
        $result            = $acourseware->updateCourseware($param);
        return $this->print_result($result);
    }
    public function editCoursewareauthorize()
    {
        if (!$this->request->isAjax()) {
            $this->res_data['Msg'] = '请求方式错误';
            return $this->print_result($this->res_data);
        }
        $param    = $this->request->param(false);
        // var_dump($param);exit;
        $acourseware= Controller('Acourseware', 'logic');
        $result            = $acourseware->updateCoursewareauthorize($param);
        return $this->print_result($result);
    }
    public function type_lists()
    {
        if ($this->request->isPost()) {
            $input = $this->request->param(false);
            $page_limit      = isset($input['length'])?$input['length']:10;
            $page_start      = isset($input['start'])?$input['start']:0;
            $p = 1;
            if ($page_start > 0) {
                $p = ceil($page_start / ($page_limit - 1));
            }
            $where = ['status'=>1];
            $count=Db::name('courseware_type')->where($where)->count();
            $list  = Db::name('courseware_type')
                  ->where($where)
                  ->limit($page_start, $page_limit)->select();
            foreach($list as &$v){
                $v['create_date'] = date('Y-m-d H:i',$v['create_time']);
            }
            
            $this->res_data['Msg']='OK';
            $this->res_data['Code']=0;
            $this->res_data['Data']=['courseware'=>$list,'Data'=>$list,'recordsTotal'=>$count];
            $this->res_data['recordsTotal']=$count;
            return $this->print_result($this->res_data);
        }
        return view('acourseware/type_lists');
    }
    public function add_type(){
        if ($this->request->isPost()) {
            $param    = $this->request->param(false);
            $acourseware= Controller('Acourseware', 'logic');
            $result            = $acourseware->add_type($param);
            return $this->print_result($result);
        }
        return view('acourseware/add_type');
    }
    public function edit_type(){
        if ($this->request->isPost()) {
            $param    = $this->request->param(false);
            $acourseware= Controller('Acourseware', 'logic');
            $result            = $acourseware->edit_type($param);
            return $this->print_result($result);
        }
        $input = $this->request->param(false);
        $id = isset($input['id'])?$input['id']:0;
        $courseware_type = [];
        if (!$id) {
            return $this->print_result(['Code'=>1,'Msg'=>'缺少参数']);
        }
        $courseware_type = Db::name('courseware_type')->where(['id'=>$id])->find();
        $this->assign('id',$id);
        $this->assign('courseware_type',$courseware_type);
        return view('acourseware/edit_type');
    }
    public function updateCoursewareType(){
        if (!$this->request->isAjax()) {
            $this->res_data['Msg'] = '请求方式错误';
            return $this->print_result($this->res_data);
        }
        $param    = $this->request->param(false);
        $acourseware= Controller('Acourseware', 'logic');
        $result            = $acourseware->updateCoursewareType($param);
        return $this->print_result($result);
    }
    public function course_lists()
    {
        if ($this->request->isPost()) {
            $input = $this->request->param(false);
            $page_limit      = isset($input['length'])?$input['length']:10;
            $page_start      = isset($input['start'])?$input['start']:0;
            $p = 1;
            if ($page_start > 0) {
                $p = ceil($page_start / ($page_limit - 1));
            }
            $where = ['status'=>1];
            $count=Db::name('courseware_course')->where($where)->count();
            $list  = Db::name('courseware_course')
                  ->where($where)
                  ->order('level DESC,sort ASC,id ASC')
                  ->limit($page_start, $page_limit)->select();
            foreach($list as &$v){
                $v['create_date'] = date('Y-m-d H:i',$v['create_time']);
                if ($v['pid']==0) {
                    $v['pname'] = '';
                } else {
                    $v['pname'] = Db::name('courseware_course')->where('id',$v['pid'])->value('name');
                }
                $v['type'] = $v['level']!=1?$v['level']==2?'课程体系':'课程主题':'课程大板块';
            }
            
            $this->res_data['Msg']='OK';
            $this->res_data['Code']=0;
            $this->res_data['Data']=['courseware'=>$list,'Data'=>$list,'recordsTotal'=>$count];
            $this->res_data['recordsTotal']=$count;
            return $this->print_result($this->res_data);
        }
        return view('acourseware/course_lists');
    }
    public function add_course(){
        if ($this->request->isPost()) {
            $param    = $this->request->param(false);
            $acourseware= Controller('Acourseware', 'logic');
            $result            = $acourseware->add_course($param);
            return $this->print_result($result);
        }
        // 所属课程板块
        $course = Db::name('courseware_course')->where(['pid'=>0,'status'=>1])->select();
        $this->assign('course',$course);
        return view('acourseware/add_course');
    }
    public function edit_course(){
        if ($this->request->isPost()) {
            $param    = $this->request->param(false);
            $acourseware= Controller('Acourseware', 'logic');
            $result            = $acourseware->edit_course($param);
            return $this->print_result($result);
        }
        $input = $this->request->param(false);
        $id = isset($input['id'])?$input['id']:0;
        $courseware_course = [];
        if (!$id) {
            return $this->print_result(['Code'=>1,'Msg'=>'缺少参数']);
        }
        $course1 = ['id'=>'','name'=>''];
        $courseware_course = Db::name('courseware_course')->where(['id'=>$id])->find();
        // $courseware_course['icon'] = config('upload_domain').$courseware_course['icon'];
        if ($courseware_course['pid']!=0) {
            $piddata = Db::name('courseware_course')->where(['id'=>$courseware_course['pid']])->find();
            if ($piddata['pid']==0) {
                $pid2=0;
                $pid1=$piddata['id'];
            } else {
                $pid2=$piddata['id'];
                $piddata = Db::name('courseware_course')->where(['id'=>$piddata['pid']])->find();
                $pid1=$piddata['id'];
                $course1 = Db::name('courseware_course')->where(['pid'=>$pid1,'status'=>1])->select();
            }
        } else {
            $pid2=0;
            $pid1=0;
        }
        // 所属课程板块
        $course = Db::name('courseware_course')->where(['pid'=>0,'status'=>1])->select();
        $this->assign('course1',$course1);
        $this->assign('course',$course);
        $this->assign('id',$id);
        $this->assign('pid1',$pid1);
        $this->assign('pid2',$pid2);
        $this->assign('courseware_course',$courseware_course);
        return view('acourseware/edit_course');
    }
    public function updateCoursewareCourse(){
        if (!$this->request->isAjax()) {
            $this->res_data['Msg'] = '请求方式错误';
            return $this->print_result($this->res_data);
        }
        $param    = $this->request->param(false);
        $acourseware= Controller('Acourseware', 'logic');
        $result            = $acourseware->updateCoursewareCourse($param);
        return $this->print_result($result);
    }
    // 所属课程的下级
    public function courseware_course_son()
    {
        if (!$this->request->isAjax()) {
            $this->res_data['Msg'] = '请求方式错误';
            return $this->print_result($this->res_data);
        }
        $param    = $this->request->param(false);
        $pid = isset($param['pid'])?intval($param['pid']):0;
        $courseware_course = Db::name('courseware_course')->where(['pid'=>$pid,'status'=>1])->select();
        $this->res_data['Msg'] = '成功';
        $this->res_data['Data'] = $courseware_course;
        $this->res_data['Code'] = 0;
        return $this->print_result($this->res_data);
    }

    // 导入
    public function import()
    {
        if (!$this->request->isPost()) {
            return view('acourseware/import');
        }
        $ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
        if(!in_array($ext,['xlsx','xls'])){
                return jsonReturn(array('ok'=>0,'msg'=>'上传格式不允许'.$_FILES['file']['name']));
        }
        if (!@move_uploaded_file($_FILES['file']["tmp_name"], config('upload_path').$_FILES['file']['name'])) {
            return jsonReturn(array('ok'=>0,'msg'=>'error|上传文件错误.'));
        }
        $file_name = config('upload_path').$_FILES['file']['name'];
        $arr = explode('.', $file_name);
        $extension = end($arr);
        require_once env('root_path')."vendor/PHPExcel/Classes/PHPExcel.php";
        require_once env('root_path')."vendor/PHPExcel/Classes/PHPExcel/IOFactory.php";
        
        $objPHPExcel = new \PHPExcel();
        if ($extension=='xlsx') {
            $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
        } else {
            $objReader = \PHPExcel_IOFactory::createReader('Excel5');
        }
        $objPHPExcel = $objReader->load($file_name,$encode='utf-8');
        $sheet = $objPHPExcel->getSheet(0);  // 第六个sheet
        $highestRow = $sheet->getHighestRow(); // 取得总行数
        if (!$highestRow) {
            return jsonReturn(array('ok'=>0,'msg'=>'该文档与以前文档不一致，请联系管理员调整参数'));
        }
        $highestColumn = $sheet->getHighestColumn(); // 取得总列数
        $insert_data = [];
        $time = time();
        Db::startTrans();
        // try {
            for ($i=2; $i <= $highestRow; $i++) { 
                $cell1 = $objPHPExcel->getActiveSheet()->getCell("B".$i)->getValue();
                $courseware_course1 = Db::name('courseware_course')->where(['name'=>$cell1,'level'=>1,'status'=>1])->find();
                if (!$courseware_course1) {
                    $data = [
                        'name' => $cell1,
                        'status' => 1,
                        'create_time' => $time,
                        'pid' => 0,
                        'level' => 1,
                    ];
                    $insert_id1 = Db::name('courseware_course')->insertGetId($data);
                    if (!$insert_id1) {
                        Db::rollBack();
                        return jsonReturn(array('ok'=>0,'msg'=>$cell1.'导入失败'));
                    }
                }

            }
            for ($i=2; $i <= $highestRow; $i++) { 
                $cell1 = $objPHPExcel->getActiveSheet()->getCell("B".$i)->getValue();
                $cell2 = $objPHPExcel->getActiveSheet()->getCell("C".$i)->getValue();
                $pid = Db::name('courseware_course')->where(['name'=>$cell1,'level'=>1,'status'=>1])->value('id');
                if ($pid) {
                    $courseware_course2 = Db::name('courseware_course')->where(['name'=>$cell2,'level'=>2,'status'=>1,'pid'=>$pid])->find();
                    if (!$courseware_course2) {
                        $data = [
                            'name' => $cell2,
                            'status' => 1,
                            'create_time' => $time,
                            'pid' => $pid,
                            'level' => 2,
                        ];
                        $insert_id2 = Db::name('courseware_course')->insertGetId($data);
                        if (!$insert_id2) {
                            Db::rollBack();
                            return jsonReturn(array('ok'=>0,'msg'=>$cell2.'导入失败'));
                        }
                    }
                }

            }
            for ($i=2; $i <= $highestRow; $i++) { 
                $cell2 = $objPHPExcel->getActiveSheet()->getCell("C".$i)->getValue();
                $cell3 = $objPHPExcel->getActiveSheet()->getCell("D".$i)->getValue();
                $cellI = (int)$objPHPExcel->getActiveSheet()->getCell("I".$i)->getValue();
                $pid = Db::name('courseware_course')->where(['name'=>$cell2,'level'=>2,'status'=>1])->value('id');
                if ($pid) {
                    $courseware_course3 = Db::name('courseware_course')->where(['name'=>$cell3,'level'=>3,'status'=>1,'pid'=>$pid])->find();
                    if (!$courseware_course3) {
                        $data = [
                            'name' => $cell3,
                            'status' => 1,
                            'create_time' => $time,
                            'pid' => $pid,
                            'level' => 3,
                            'sort' => $cellI,
                        ];
                        $insert_id3 = Db::name('courseware_course')->insertGetId($data);
                        if (!$insert_id3) {
                            Db::rollBack();
                            return jsonReturn(array('ok'=>0,'msg'=>$cell3.'导入失败'));
                        }
                    } else {
                        $data = [
                            'name' => $cell3,
                            'status' => 1,
                            'update_time' => $time,
                            'pid' => $pid,
                            'level' => 3,
                        ];
                        if (isset($cellI)) {
                            $data['sort'] = $cellI;
                        }
                        $insert_id3 = Db::name('courseware_course')->where('id',$courseware_course3['id'])->update($data);
                        // if (!$insert_id3) {
                        //     Db::rollBack();
                        //     return jsonReturn(array('ok'=>0,'msg'=>$cell3.'导入失败'));
                        // }
                    }
                }

            }
            // 课件
            for ($i=2; $i <= $highestRow; $i++) { 
                // if ($i==2) {
                //     $is_update = Db::name('courseware')->where(['status'=>1])->update(['status'=>0]);
                // }
                $cell3 = $objPHPExcel->getActiveSheet()->getCell("D".$i)->getValue();
                $cellA = $objPHPExcel->getActiveSheet()->getCell("A".$i)->getValue();
                $cell2 = $objPHPExcel->getActiveSheet()->getCell("C".$i)->getValue();
                $pid = Db::name('courseware_course')->where(['name'=>$cell2,'level'=>2,'status'=>1])->value('id');
                if (!$pid) continue;
                $courseware_course3 = Db::name('courseware_course')->where(['name'=>$cell3,'level'=>3,'status'=>1,'pid'=>$pid])->find();
                if ($courseware_course3) {
                    $courseware = Db::name('courseware')->where(['name'=>$cellA,'course'=>$courseware_course3['name'],'status'=>1,'course_id'=>$courseware_course3['id']])->find();
                    if (!$courseware) {
                        $name = $cellA;
                        $course_id = $courseware_course3['id'];
                        $main_point = $objPHPExcel->getActiveSheet()->getCell("E".$i)->getValue();
                        $teaching_aims = $objPHPExcel->getActiveSheet()->getCell("F".$i)->getValue();
                        $course = $courseware_course3['name'];
                        $status = 1;
                        $file = $objPHPExcel->getActiveSheet()->getCell("G".$i)->getValue();
                        $file_arr = explode(',', $file);
                        if ($file_arr) {
                            $file = [];
                            foreach ($file_arr as $key => $value) {
                                $arr = explode('.', $value);
                                $extension = end($arr);
                                $fileres = Db::name('file')->where(['name'=>$value])->find();
                                if ($extension=='mp4') {
                                    $file[] = ['2','cljy/'.$value,'视频'];
                                } elseif (in_array($extension, ['xlsx','xls','doc','docx','ppt','pptx'])) {
                                    $file[] = ['3','cljy/'.$value,'文档'];
                                } elseif ($extension=='pdf') {
                                    $file[] = ['1','cljy/'.$value,'pdf'];
                                }
                                if (!$fileres) {
                                    if (!Db::name('file')->insertGetId([
                                        'name' => $value,
                                        'path' => 'cljy/'.$value,
                                        'create_time' => $time,
                                        'extension' => $extension,
                                    ])) {
                                        Db::rollBack();
                                        return jsonReturn(array('ok'=>0,'msg'=>$cellA.'文件导入失败'));
                                    }
                                }
                            }
                        }
                        $data = [
                            'name' => $name,
                            'course' => $course,
                            'file' => json_encode($file,1),
                            'status' => $status,
                            'create_time' => $time,
                            'course_id' => $course_id,
                            'main_point' => $main_point,
                            'teaching_aims' => $teaching_aims,
                        ];
                        $insert_id4 = Db::name('courseware')->insertGetId($data);
                        if (!$insert_id4) {
                            Db::rollBack();
                            return jsonReturn(array('ok'=>0,'msg'=>$cellA.'导入失败'));
                        }
                    } else {
                        $name = $cellA;
                        $course_id = $courseware_course3['id'];
                        $main_point = $objPHPExcel->getActiveSheet()->getCell("E".$i)->getValue();
                        $teaching_aims = $objPHPExcel->getActiveSheet()->getCell("F".$i)->getValue();
                        $course = $courseware_course3['name'];
                        $status = 1;
                        $file = $objPHPExcel->getActiveSheet()->getCell("G".$i)->getValue();
                        $file_arr = explode(',', $file);
                        if ($file_arr) {
                            $file = [];
                            foreach ($file_arr as $key => $value) {
                                $arr = explode('.', $value);
                                $extension = end($arr);
                                $fileres = Db::name('file')->where(['name'=>$value])->find();
                                if ($extension=='mp4') {
                                    $file[] = ['2','cljy/'.$value,'视频'];
                                } elseif (in_array($extension, ['xlsx','xls','doc','docx','ppt','pptx'])) {
                                    $file[] = ['3','cljy/'.$value,'文档'];
                                } elseif ($extension=='pdf') {
                                    $file[] = ['1','cljy/'.$value,'pdf'];
                                }
                                if (!$fileres) {
                                    if (!Db::name('file')->insertGetId([
                                        'name' => $value,
                                        'path' => 'cljy/'.$value,
                                        'create_time' => $time,
                                        'extension' => $extension,
                                    ])) {
                                        Db::rollBack();
                                        return jsonReturn(array('ok'=>0,'msg'=>$cellA.'文件导入失败'));
                                    }
                                }
                            }
                        }
                        $data = [
                            'name' => $name,
                            'course' => $course,
                            'file' => json_encode($file,1),
                            'status' => $status,
                            'create_time' => $time,
                            'course_id' => $course_id,
                            'main_point' => $main_point,
                            'teaching_aims' => $teaching_aims,
                        ];
                        $insert_id4 = Db::name('courseware')->where(['id'=>$courseware['id']])->update(['file'=>json_encode($file,1),'main_point'=>$main_point,'teaching_aims'=>$teaching_aims,'update_time'=>$time]);
                        // if (!$insert_id4) {
                        //     Db::rollBack();
                        //     return jsonReturn(array('ok'=>0,'msg'=>$cellA.'导入失败'));
                        // }
                    }
                }

            }
            // 授权
            $sidarr = [];
            for ($i=2; $i <= $highestRow; $i++) { 
                $cell2 = $objPHPExcel->getActiveSheet()->getCell("H".$i)->getValue();
                if (!$cell2) {
                    continue;
                }
                $cell3 = $objPHPExcel->getActiveSheet()->getCell("D".$i)->getValue();
                $cell31 = $objPHPExcel->getActiveSheet()->getCell("D".($i-1))->getValue();
                if (isset($cell31) && $cell31 && $cell31==$cell3) {
                    continue;
                }
                $cellA = $objPHPExcel->getActiveSheet()->getCell("A".$i)->getValue();
                $cell2c = $objPHPExcel->getActiveSheet()->getCell("C".$i)->getValue();
                $pid = Db::name('courseware_course')->where(['name'=>$cell2c,'level'=>2,'status'=>1])->value('id');
                if (!$pid) continue;
                $courseware_course3 = Db::name('courseware_course')->where(['name'=>$cell3,'level'=>3,'status'=>1,'pid'=>$pid])->find();
                if ($courseware_course3) {
                    $courseware = Db::name('courseware')->where(['name'=>$cellA,'course'=>$courseware_course3['name'],'status'=>1,'course_id'=>$courseware_course3['id']])->find();
                    // 之前的授权状态改掉
                    $courseware_authorize = Db::name('courseware_authorize')->where(['courseware_id'=>$courseware['id'],'status'=>1,'type'=>1])->find();
                    if ($courseware_authorize) {
                        $is_update = Db::name('courseware_authorize')->where(['courseware_id'=>$courseware['id'],'status'=>1,'type'=>1])->update(['status'=>0,'update_time'=>$time]);
                        if (!$is_update) {
                            Db::rollBack();
                            return jsonReturn(array('ok'=>0,'msg'=>$cellA.'授权失败'));
                        }
                    }
                    $courseware_authorize = Db::name('courseware_authorize')->where(['course_id'=>$courseware_course3['id'],'status'=>1,'type'=>1])->group('sid')->select();
                    if ($i==2) {
                        foreach ($courseware_authorize as $key => $value) {
                            $sidarr[$value['sid']]['start_time'] = $value['start_time'];
                            $sidarr[$value['sid']]['end_time'] = $value['end_time'];
                        }
                    }
                    if ($courseware_authorize) {
                        $is_update = Db::name('courseware_authorize')->where(['course_id'=>$courseware_course3['id'],'status'=>1,'type'=>1])->update(['status'=>0,'update_time'=>$time]);
                        if (!$is_update) {
                            Db::rollBack();
                            return jsonReturn(array('ok'=>0,'msg'=>$cellA.'授权失败'));
                        }
                    }
                    $cell2_arr = explode(',', $cell2);
                    foreach ($cell2_arr as $kk => $vv) {
                        $sid = Db::name('store')->where('name',$vv)->value('id');
                        // $courseware_authorize = Db::name('courseware_authorize')->where(['sid'=>$sid,'courseware_id'=>$courseware['id'],'status'=>1,'type'=>1])->find();
                        // if (!$courseware_authorize) {
                            $data5 = [
                                'sid' => $sid,
                                'course_id' => $courseware_course3['id'],
                                'status' => 1,
                                'type' => 1,
                                'create_time' => time(),
                            ];
                            if (isset($sidarr[$sid]['start_time'])) {
                                $data5['start_time'] = $sidarr[$sid]['start_time'];
                                $data5['end_time'] = $sidarr[$sid]['end_time'];
                            }
                            $insert_id5 = Db::name('courseware_authorize')->insertGetId($data5);
                            if (!$insert_id5) {
                                Db::rollBack();
                                return jsonReturn(array('ok'=>0,'msg'=>$cellA.'授权失败'));
                            }
                        // }
                    }
                }

            }
            // 授权第一级主题
            for ($i=2; $i <= $highestRow; $i++) { 
                $cell2 = $objPHPExcel->getActiveSheet()->getCell("H".$i)->getValue();
                if (!$cell2) {
                    continue;
                }
                $cellB = $objPHPExcel->getActiveSheet()->getCell("B".$i)->getValue();
                $cellB1 = $objPHPExcel->getActiveSheet()->getCell("B".($i-1))->getValue();
                if (isset($cellB1) && $cellB1 && $cellB1==$cellB) {
                    continue;
                }
                $cellA = $objPHPExcel->getActiveSheet()->getCell("A".$i)->getValue();
                $courseware_course3 = Db::name('courseware_course')->where(['name'=>$cellB,'level'=>1,'status'=>1])->find();
                if ($courseware_course3) {
                    $courseware_authorize = Db::name('courseware_authorize')->where(['course_id'=>$courseware_course3['id'],'status'=>1,'type'=>1])->group('sid')->select();
                    // if ($i==2) {
                    //     foreach ($courseware_authorize as $key => $value) {
                    //         $sidarr[$value['sid']]['start_time'] = $value['start_time'];
                    //         $sidarr[$value['sid']]['end_time'] = $value['end_time'];
                    //     }
                    // }
                    if ($courseware_authorize) {
                        $is_update = Db::name('courseware_authorize')->where(['course_id'=>$courseware_course3['id'],'status'=>1,'type'=>1])->update(['status'=>0,'update_time'=>$time]);
                        if (!$is_update) {
                            Db::rollBack();
                            return jsonReturn(array('ok'=>0,'msg'=>$cellA.'授权失败'));
                        }
                    }
                    $cell2_arr = explode(',', $cell2);
                    foreach ($cell2_arr as $kk => $vv) {
                        $sid = Db::name('store')->where('name',$vv)->value('id');
                        // $courseware_authorize = Db::name('courseware_authorize')->where(['sid'=>$sid,'courseware_id'=>$courseware['id'],'status'=>1,'type'=>1])->find();
                        // if (!$courseware_authorize) {
                            $data5 = [
                                'sid' => $sid,
                                'course_id' => $courseware_course3['id'],
                                'status' => 1,
                                'type' => 1,
                                'create_time' => time(),
                            ];
                            if (isset($sidarr[$sid]['start_time'])) {
                                $data5['start_time'] = $sidarr[$sid]['start_time'];
                                $data5['end_time'] = $sidarr[$sid]['end_time'];
                            }
                            $insert_id5 = Db::name('courseware_authorize')->insertGetId($data5);
                            if (!$insert_id5) {
                                Db::rollBack();
                                return jsonReturn(array('ok'=>0,'msg'=>$cellA.'授权失败'));
                            }
                        // }
                    }
                }

            }
            // 授权第二级主题
            for ($i=2; $i <= $highestRow; $i++) { 
                $cell2 = $objPHPExcel->getActiveSheet()->getCell("H".$i)->getValue();
                if (!$cell2) {
                    continue;
                }
                $cellC = $objPHPExcel->getActiveSheet()->getCell("C".$i)->getValue();
                $cellC1 = $objPHPExcel->getActiveSheet()->getCell("C".($i-1))->getValue();
                if (isset($cellC1) && $cellC1 && $cellC1==$cellC) {
                    continue;
                }
                $cellA = $objPHPExcel->getActiveSheet()->getCell("A".$i)->getValue();
                $courseware_course3 = Db::name('courseware_course')->where(['name'=>$cellC,'level'=>2,'status'=>1])->find();
                if ($courseware_course3) {
                    $courseware_authorize = Db::name('courseware_authorize')->where(['course_id'=>$courseware_course3['id'],'status'=>1,'type'=>1])->group('sid')->select();
                    // if ($i==2) {
                    //     foreach ($courseware_authorize as $key => $value) {
                    //         $sidarr[$value['sid']]['start_time'] = $value['start_time'];
                    //         $sidarr[$value['sid']]['end_time'] = $value['end_time'];
                    //     }
                    // }
                    if ($courseware_authorize) {
                        $is_update = Db::name('courseware_authorize')->where(['course_id'=>$courseware_course3['id'],'status'=>1,'type'=>1])->update(['status'=>0,'update_time'=>$time]);
                        if (!$is_update) {
                            Db::rollBack();
                            return jsonReturn(array('ok'=>0,'msg'=>$cellA.'授权失败'));
                        }
                    }
                    $cell2_arr = explode(',', $cell2);
                    foreach ($cell2_arr as $kk => $vv) {
                        $sid = Db::name('store')->where('name',$vv)->value('id');
                        // $courseware_authorize = Db::name('courseware_authorize')->where(['sid'=>$sid,'courseware_id'=>$courseware['id'],'status'=>1,'type'=>1])->find();
                        // if (!$courseware_authorize) {
                            $data5 = [
                                'sid' => $sid,
                                'course_id' => $courseware_course3['id'],
                                'status' => 1,
                                'type' => 1,
                                'create_time' => time(),
                            ];
                            if (isset($sidarr[$sid]['start_time'])) {
                                $data5['start_time'] = $sidarr[$sid]['start_time'];
                                $data5['end_time'] = $sidarr[$sid]['end_time'];
                            }
                            $insert_id5 = Db::name('courseware_authorize')->insertGetId($data5);
                            if (!$insert_id5) {
                                Db::rollBack();
                                return jsonReturn(array('ok'=>0,'msg'=>$cellA.'授权失败'));
                            }
                        // }
                    }
                }

            }
            Db::commit();
            return jsonReturn(array('ok'=>1,'msg'=>'导入成功'));
            echo 'success';
        // } catch (\Exception $e) {
        //     Db::rollBack();
        //     return jsonReturn(array('ok'=>0,'msg'=>'导入失败'));
        // }
    }
}
